package com.leyou.user.web;

import com.leyou.auth.dto.UserDetails;
import com.leyou.auth.thread.UserContext;
import com.leyou.common.exceptions.LyException;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.service.UserService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@RestController
@RequestMapping("/info")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 校验用户数据是否存在
     * @param data 要校验的数据
     * @param type 校验数据的类型，1用户名、2手机号
     * @return true：存在，false：不存在
     */
    @GetMapping("/exists/{data}/{type}")
    public ResponseEntity<Boolean> checkData(
            @PathVariable("data") String data, @PathVariable("type") Integer type){
        Boolean isExists = userService.checkData(data, type);
        return ResponseEntity.ok(isExists);
    }

    /**
     * 发送短信验证码
     * @param phone 手机号
     * @return 无
     */
    @PostMapping("/code")
    public ResponseEntity<Void> sendVerifyCode(@RequestParam("phone") String phone){
        userService.sendVerifyCode(phone);
        return ResponseEntity.noContent().build();
    }

    /**
     * 注册用户
     * @param user 用户信息
     * @param code 验证码
     * @return 无
     */
    @PostMapping
    public ResponseEntity<Void> register(@Valid User user, BindingResult result, @RequestParam("code") String code){
        // 自己判断是否有错误
        if(result.hasErrors()){
            String msg = result.getFieldErrors().stream()
                    .map(FieldError::getDefaultMessage).collect(Collectors.joining("|"));
            throw new LyException(400, msg + ", 再捣乱我就报警了！");
        }
        userService.register(user, code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 根据用户名和密码查询用户
     * @param username 用户名
     * @param password 密码
     * @return 用户信息
     */
    @GetMapping
    public ResponseEntity<UserDTO> queryUserByUsernameAndPassword(
            @RequestParam("username") String username,@RequestParam("password") String password
    ){
        return ResponseEntity.ok(userService.queryUserByUsernameAndPassword(username, password));
    }

    /**
     * 查询当前登录的用户信息
     * @return 用户名
     */
    @GetMapping("me")
    public ResponseEntity<UserDetails> me(){
        return ResponseEntity.ok(UserContext.getUser());
    }
}